﻿using Game.NetWork.Packages;
using Game.NetWork;
using Engine;
using System;
using System.Text;
using System.Collections.Generic;
using static Game.MusketBlock;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;
using GameEntitySystem;
using TemplatesDatabase;

namespace Game.Server.EssentialCmd
{
    public class CmdClearGroup : AbstractProcessCmd
    {
        public override string Cmd => "clgp";
        public override string Introduce => "/clgp all  -清除所有队伍";
        public override int AuthLevel => 100;
        public override DisplayType Display => DisplayType.All;

        public override void ProcessCmd()
        {
            if (GameManager.Project == null) return;
            if (m_messageDatas.Length >= 2)
            {
                if(m_messageDatas[1] == "all")
                {
                    try
                    {
                        SubsystemPlayers subsystemPlayers = GameManager.Project.FindSubsystem<SubsystemPlayers>();
                        List<PlayerData> playerDatas = new List<PlayerData>();
                        playerDatas.AddRange(subsystemPlayers.PlayersData);
                        foreach (var pla in playerDatas)
                        {
                            subsystemPlayers.RemovePlayerData(pla, true);
                        }
                        Console.WriteLine($"已成功清空玩家");
                        string worldPath = GameManager.Project.FindSubsystem<SubsystemGameInfo>().DirectoryName;
                        string path = Storage.CombinePaths(worldPath, "PlayerEntities");
                        if (Storage.DirectoryExists(path))
                        {
                            List<Guid> guids = new List<Guid>();
                            foreach (string guid in Storage.ListFileNames(path))
                            {
                                Guid guid2 = new Guid(guid.Split(new char[1] { '.' })[0]);
                                if (!guids.Contains(guid2))
                                {
                                    guids.Add(guid2);
                                }
                            }
                            foreach (Guid guid in guids)
                            {
                                if (subsystemPlayers.CheckPlayerDataExists(guid, out string palyerPath))
                                {
                                    ValuesDictionary dict = new ValuesDictionary();
                                    using (Stream s = Storage.OpenFile(palyerPath, OpenFileMode.Read))
                                    {
                                        byte[] d = new byte[s.Length];
                                        s.Read(d, 0, d.Length);
                                        dict.ApplyOverridesUseMessagePack(d);
                                    }
                                    ValuesDictionary data = dict.GetValue<ValuesDictionary>("Data");
                                    data.SetValue("GroupKey", string.Empty);
                                    using (Stream stream = Storage.OpenFile(palyerPath, OpenFileMode.Create))
                                    {
                                        byte[] array = dict.ToMessagePack();
                                        stream.Write(array, 0, array.Length);
                                        stream.Flush();
                                    }
                                    using (Stream stream = Storage.OpenFile(palyerPath.Replace(".dat", ".json"), OpenFileMode.Create))
                                    {
                                        StreamWriter streamWriter = new StreamWriter(stream);
                                        streamWriter.Write(dict.ToJsonText());
                                        streamWriter.Flush();
                                        streamWriter.Dispose();
                                    }
                                }
                            }
                        }
                        subsystemPlayers.ServerGroups.Clear();
                        SendMessage(Cmd, "队伍清空成功，请重新进入存档");
                        GameManager.SaveProject(true, false);
                        GameManager.DisposeProject();
                        CommonLib.Net.Stop();
                        ScreensManager.SwitchScreen("Play");
                    }
                    catch
                    {
                        SendMessage(Cmd, "输入有误，请重试");
                    }
                }
            }
            else
            {
                SendMessage(Cmd, "/clgp all  -清除所有队伍");
            }
        }
    }

}